# src/models/user.py

from src.config.database import DatabaseConfig
from src.utils.password_util import PasswordUtil
from src.utils.exceptions import UserNotFoundException, PasswordIncorrectException

class User:
    def __init__(self):
        self.db_config = DatabaseConfig()

    def find_user_by_username(self, username):
        """根据用户名查找用户"""
        try:
            connection = self.db_config.get_connection()
            with connection:
                with connection.cursor() as cursor:
                    sql = """
                        SELECT id,username,`password`,age,user_role,male,create_time,update_time,tags 
                        FROM mk_user 
                        WHERE username = %s 
                    """
                    cursor.execute(sql, (username,))
                    result = cursor.fetchone()
                    return result
        except Exception as e:
            raise Exception(f"查询用户失败: {str(e)}")

    def verify_login(self, username, password):
        """验证登录"""
        try:
            # 查找用户
            user = self.find_user_by_username(username)

            if not user:
                raise UserNotFoundException("用户不存在")

            # 验证密码
            if not PasswordUtil.verify_password(password, user['password']):
                raise PasswordIncorrectException("密码错误")

            # 返回用户信息（不包含密码）
            user_info = {
                'id': user['id'],
                'username': user['username'],
                'age': user['age'],
                'user_role': user['user_role'],
                'male': user['male'],
                'create_time': str(user['create_time']) if user['create_time'] else None,
                'update_time': str(user['update_time']) if user['update_time'] else None,
                'tags': user['tags']
            }

            return user_info

        except (UserNotFoundException, PasswordIncorrectException) as e:
            raise e
        except Exception as e:
            raise Exception(f"登录验证失败: {str(e)}")
